<template>
    <view class="page">
        <view class="head-wrap">
            <view class="text">头像</view>
            <view class="head" @click="handleHead"><image :src="showHead"></image></view>
        </view>
        <view class="list">
            <view class="text">昵称</view>
            <view class="input-wrap">
                <input type="text" class="input" placeholder="请输入昵称" v-model="nickname" />
            </view>
        </view>
        <view class="list">
            <view class="text">姓名</view>
            <view class="input-wrap">
                <input type="text" class="input" placeholder="请输入姓名" v-model="name" />
            </view>
        </view>
        <view class="list" @click="selectGender">
            <view class="text">性别</view>
            <view class="input-wrap">
                <view class="text-tip">{{gender=='1'?'男':gender=='2'?'女':'请选择'}}</view>
                <view class="arrow"></view>
            </view>
        </view>
        <button type="button" class="submit-btn" @click="submit()">保存</button>
    </view>
</template>

<script>
    import {mapActions,mapState} from "vuex";
    export default {
        name: "profile",
        data(){
            return {
                branch_shop_id: "",
                table_code: "",
                showHead:"../../static/images/user/head.png",//显示头像
                gender:"",//性别
                nickname:"",//昵称
                name:"",//姓名
                head:"",//保存到数据库的头像图片名称
                isSubmit: true
            }
        },
        onLoad(opts){
            this.branch_shop_id = opts.branch_shop_id || "";
            this.table_code = opts.table_code || "";
            this.isSubmit = true;
            this.$utils.safeUser(this, this.branch_shop_id, this.table_code, () => {
                this.getUserInfo({
                    branch_shop_id: this.branch_shop_id,
                    success: (data) => {
                        this.name = data.name || "";
                        this.nickname = data.nickname || "";
                        this.gender = data.gender || "";
                        this.showHead = data.head || "../../static/images/user/head.png";
                        this.head = data.head || "";
                    }
                });
            });
        },
        computed:{
            ...mapState({
                uid:state=>state.user.uid,
                token:state=>state.user.token,
                platform:state=>state.system.platform
            })
        },
        methods:{
            ...mapActions({
                getUserInfo:"user/getUserInfo",//获取会员信息
                updateUser:"user/updateUser"//修改会员信息
            }),
            //操作头像
            handleHead(){
                uni.showActionSheet({
                    itemList: ['拍照', '从相册选择'],
                    success: (res)=> {
                        let sourceType=[];
                        if(res.tapIndex==0){
                            sourceType=['camera'];//拍照
                        }else if(res.tapIndex==1){
                            sourceType=['album'];//从相册选择
                        }
                        //选择图片
                        uni.chooseImage({
                            count: 1,                            
                            sizeType: ['original', 'compressed'], 
                            sourceType: sourceType,
                            success: (res)=> {
                                let tempFilePath=res.tempFilePaths[0];
                                this.showHead=tempFilePath;
                                //上传头像
                                this.uploadHead(tempFilePath);
                            }
                        });
                    },
                    fail: (res)=> {
                        console.log("选择图片失败:", res.errMsg);
                    }
                });
            },
            // 上传头像API
            uploadHead(filePath) {
                // 创建上传任务
                const uploadTask = uni.uploadFile({
                    url: 'https://diancan.frp.feashow.cn/api.php/v1/user/uploadhead',
                    filePath: filePath,
                    name: 'head',
                    formData: {
                        uid: this.uid,
                        token: this.token,
                        platform: this.platform
                    },
                    success: (uploadRes) => {
                        console.log('上传头像响应:', uploadRes);
                        try {
                            const data = JSON.parse(uploadRes.data);
                            if (data.status === 1 && data.code === 200) {
                                this.head = data.data.msbox;
                                uni.showToast({ title: "头像上传成功", icon: "success" });
                            } else {
                                console.error('头像上传失败:', data);
                                uni.showToast({ title: data.data || "头像上传失败", icon: "none" });
                            }
                        } catch (e) {
                            console.error('解析头像响应失败:', e);
                            uni.showToast({ title: "头像上传失败", icon: "none" });
                        }
                    },
                    fail: (err) => {
                        console.error('上传头像请求失败:', err);
                        uni.showToast({ title: "头像上传失败", icon: "none" });
                    }
                });
                
                // 监听上传进度
                uploadTask.onProgressUpdate((res) => {
                    console.log('上传进度:', res.progress);
                });
            },
            //选择性别
            selectGender(){
                uni.showActionSheet({
                    itemList: ['男', '女'],
                    success:  (res)=> {
                        this.gender = (res.tapIndex == 0) ? '1' : '2';
                    },
                    fail: function (res) {
                        console.log("选择性别失败:", res.errMsg);
                    }
                });
            },
            //保存用户信息
            submit(){
                if(this.isSubmit){
                    if(this.nickname.trim()==''){
                        uni.showToast({
                            title: '请输入昵称',
                            icon: 'none',
                            duration:2000
                        })
                        return;
                    }
                    if(this.name.trim()==''){
                        uni.showToast({
                            title: '请输入姓名',
                            icon: 'none',
                            duration:2000
                        })
                        return;
                    }
                    if(String(this.gender).trim()==''){
                        uni.showToast({
                            title: '请选择性别',
                            icon: 'none',
                            duration:2000
                        })
                        return;
                    }
                    this.isSubmit=false;
                    this.updateUser({
                        branch_shop_id: this.branch_shop_id,
                        name: this.name,
                        nickname: this.nickname,
                        gender: this.gender,
                        head: this.head,
                        success: ()=>{
                            uni.showToast({
                                title:"保存成功！",
                                icon:"none",
                                duration:2000
                            });
                            setTimeout(()=>{
                                uni.navigateBack({ delta: 1 })
                            },2000)
                        },
                        error: (err) => {
                            console.error('更新用户信息失败:', err);
                            uni.showToast({
                                title: err?.data || "保存失败，请重试",
                                icon: "none",
                                duration: 2000
                            });
                            this.isSubmit = true;
                        }
                    })
                }
            }
        }
    }
</script>

<style scoped>
    .page{width:100%;height:100vh;overflow:hidden;background-color:#FFFFFF;}
    .head-wrap{width:100%;height:120rpx;border-bottom: 1px solid #EFEFEF;display:flex;justify-content: space-between;align-items: center;box-sizing: border-box;padding:0px 30rpx;}
    .head-wrap .text,.list .text{font-size:28rpx;color:#333333;}
    .head-wrap .head{width:100rpx;height:100rpx;}
    .head-wrap .head image{width:100%;height:100%;border-radius: 100%;}
    .list{width:100%;height:80rpx;border-bottom: 1px solid #EFEFEF;display:flex;justify-content: space-between;align-items: center;box-sizing: border-box;padding:0px 30rpx;}
    .list .input-wrap{width:auto;height:100%;display:flex;align-items: center;}
    .list .input-wrap .input{width:380rpx;height:66rpx;font-size:28rpx;text-align:right;}
    .list .arrow{width:40rpx;height:40rpx;background-image: url("~@/static/images/user/right_arrow.png");background-size:100%;background-repeat: no-repeat;background-position: center;margin-left:20rpx;}
    .list .text-tip{font-size:28rpx;color:#333333;}
    .submit-btn{width:200rpx;height:60rpx;margin:0 auto;background-color:#E30019;color:#FFFFFF;font-size:28rpx;margin-top:40rpx;line-height:60rpx;border-radius: 4px;}
</style>